<template>
  <el-breadcrumb class="breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) of levelList" :key="item.path">
        <span
          v-if="item.redirect === 'noRedirect' || index === levelList.length - 1"
          class="no-redirect"
        >{{item.meta.title}}</span>
        <a v-else @click.prevent="handleLink(item)">{{item.meta.title}}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>
import { compile } from 'path-to-regexp'

export default {
  data() {
    return {
      levelList: null
    }
  },
  props: {
    indexPath: {
      type: String,
      required: true
    },
    indexTitle: {
      type: String,
      required: true
    }
  },
  watch: {
    $route(route) {
      // 如果转向重定向页面 不要更新面包屑
      if (route.path.startsWith('/redirect/')) {
        return
      }
      this.getBreadcrumb()
    }
  },
  created() {
    this.getBreadcrumb()
  },
  methods: {
    getBreadcrumb() {
      let matched = this.$route.matched.filter(
        item => item.meta && item.meta.title
      )

      const first = matched[0]

      if (!this.isDashboard(first)) {
        matched = [
          { path: this.indexPath, meta: { title: this.indexTitle } }
        ].concat(matched)
      }

      this.levelList = matched.filter(
        item => item.meta && item.meta.title && item.meta.breadcrumb !== false
      )
    },
    isDashboard(route) {
      const path = route && route.path
      if (!path) {
        return false
      }
      return (
        path.trim().toLocaleLowerCase() === this.indexPath.toLocaleLowerCase()
      )
    },
    pathCompile(path) {
      const { params } = this.$route
      let toPath = compile(path)
      return toPath(params)
    },
    handleLink(item) {
      const { redirect, path } = item
      if (redirect) {
        this.$router.push(redirect)
        return
      }
      this.$router.push(this.pathCompile(path))
    }
  }
}
</script>
